/**
 * @param {number[][]} grid
 * @return {number}
 */
var maxAreaOfIsland = function(grid) {
    let i= -1;
    let max = 0;

    for (const row of grid) {
        i++;
        let j = -1;

        for (const cel of row) {
            j++;
            if (grid[i][j] === 1) {
                const result = dfs(grid, i, j);
                max = Math.max(result, max);
            }
        }
    }

    return max;
};

// 盘子，行，列，当前数量，方向
function dfs(grid, i, j, count=0) {
    grid[i][j] = 0; // 已统计过的，设为海洋
    count += 1;

    const list = [
        [i-1, j],
        [i+1, j],
        [i, j-1],
        [i, j+1],
    ];
    
    while(list.length) {
        const item = list.shift();
        if (grid[item[0]]?.[item[1]] !== 1) continue;
        count = dfs(grid, item[0], item[1], count);
    }

    return count;
}

// const grid = [[0,0,1,0,0,0,0,0,0,0,0,0,0],[0,0,1,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0]];
// const grid = [
//     [1,1,0,0,0],
//     [1,1,0,0,0],
//     [0,0,0,1,1],
//     [0,0,0,1,1]
// ];
const grid = [
    [0,0,1,0,0,0,0,1,0,0,0,0,0],
    [0,0,0,0,0,0,0,1,1,1,0,0,0],
    [0,1,1,0,1,0,0,0,0,0,0,0,0],
    [0,1,0,0,1,1,0,0,1,0,1,0,0],
    [0,1,0,0,1,1,0,0,1,1,1,0,0],
    [0,0,0,0,0,0,0,0,0,0,1,0,0],
    [0,0,0,0,0,0,0,1,1,1,0,0,0],
    [0,0,0,0,0,0,0,1,1,0,0,0,0]
];
console.log(maxAreaOfIsland(grid));